<script setup lang="ts">
import { ref,computed } from "vue";
import { useChooseStore } from "@/stores/choosePageStore";  
import {apiQuick} from "../../../apis/apis.js"
import{onShow} from "@dcloudio/uni-app"
const appStore = useChooseStore()
const currentYear =new Date().getFullYear() 
const currentMonth= new Date().getMonth() + 1
const selectedDate = ref([
  { value: currentYear, text: `${currentYear}年` },
  { value: currentMonth, text: `${currentMonth}月` }
]);
//将selectedDate的值转换为字符串，格式为xxxx-xx

// const getRecordCount = async () => {
//   try {
//     const res = await apiQuick("combine",{uid:appStore.uid,date:selectedDateString.value})
//     console.log(res.data);
//     return res.data.rows.length;
//   } catch (error) {
//     console.error(error);
//     return 0;
//   }
// }

const years = Array.from({ length: 10 }, (_, i) => {
  const year = new Date().getFullYear() - i;
  return {
    text: `${year}年`,
    value: year,
    children: Array.from({ length: 12 }, (_, j) => ({
      text: `${j + 1}月`,
      value: j + 1,
    })),
  };
});
selectedDate.value = [
  { value: currentYear, text: `${currentYear}年` },
  { value: currentMonth, text: `${currentMonth}月` }
];

// getRecordCount()
const emit = defineEmits(["update:date"]);

const handleDateChange = (e: any) => {
  if (e.detail.value.length === 2) {
    const selected = e.detail.value.map((item: any) => item.value); // [year, month]
    selectedDate.value = selected;

    emit("update:date", selected);

    // 正确转换为 yyyy-MM 格式
    const year = selected[0];
    const month = String(selected[1]).padStart(2, '0');
    const dateStr = `${year}-${month}`;

    appStore.setChooseDate2(dateStr);

    console.log("统一后的 selectedDate:", selected);
    console.log("已传给 Pinia 的 chooseDate:", appStore.chooseDate2);  //  应为 2025-02
  }
};
console.log(selectedDate.value);


// 添加记录数量属性
const props = defineProps({
  recordCount: {
    type: Number,
    default: 0,
  },
});
onShow(() => {
  const [yearObj, monthObj] = selectedDate.value;
  const year = yearObj.value;
  const month = String(monthObj.value).padStart(2, '0');
  const dateStr = `${year}-${month}`;
  appStore.setChooseDate2(dateStr);
  console.log("chooseDate 初始化:", appStore.chooseDate2);
})
</script>

<template>
  <view class="header">
    <uni-data-picker
      class="date-picker"
      v-model="selectedDate"
      :localdata="years"
      :clear-icon="false"
      popup-title="选择年月"
      @change="handleDateChange"
    />
    <view class="record-count">共{{ appStore.count2 }}条记录</view>
  </view>
</template>

<style scoped lang="scss">
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #ffffff;
  border-radius: 12rpx;

  .date-picker {
    flex: 1;
  }

  .record-count {
    margin-left: 30rpx;
    color: #666666;
    font-size: 28rpx;
  }
}
</style>
